package com.fish.yssb.ui.page.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;

import com.fish.yssb.R;
import com.fish.yssb.ui.page.activity.base.BaseActivity;
import com.fish.yssb.ui.page.fragment.LSFragment;
import com.fish.yssb.ui.page.fragment.MainFragment;
import com.jaeger.library.StatusBarUtil;

import java.util.ArrayList;
import java.util.List;


public class MainActivity extends BaseActivity implements OnClickListener {
    //声明ViewPager
    private ViewPager mViewPager;

    //适配器
    private FragmentPagerAdapter mAdapter;
    private String[] mPermissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};

    private AlertDialog mDialog;
    //装载Fragment的集合
    private List<Fragment> mFragments;

    //四个Tab对应的布局
    private LinearLayout mTabWeixin;
    private LinearLayout mTabFrd;
    private LinearLayout mTabAddress;
//    private LinearLayout mTabSetting;

    //四个Tab对应的ImageButton
    private ImageButton mImgWeixin;
    private ImageButton mImgFrd;
    private ImageButton mImgAddress;
    private ImageButton mImgSetting;
    private TextView mTvMainTop;
    private RelativeLayout main_top_ll;
    private TextView mHomeTv, mProjectsTv, mMsgtv, mMain_allread;


    public static void start(Context context) {
        Intent intent = new Intent(context, MainActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        StatusBarUtil.setTransparent(MainActivity.this);
        StatusBarUtil.setDarkMode(this);
        setContentView(R.layout.activity_main);

        requestPermission();
        initViews();//初始化控件
        initEvents();//初始化事件
        initDatas();//初始化数据
//
        setTimer();
//        Window window = getWindow();
//        //取消设置透明状态栏,使 ContentView 内容不再覆盖状态栏
//        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//
//        //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
//        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
//
//        //设置状态栏字体颜色为黑色
//        window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
//
//        window.setStatusBarColor(getResources().getColor(R.color.page_top));
//        //设置状态栏字体颜色为白色
//        window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
//        shapeLoadingDialog = new ShapeLoadingDialog(this);


    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
//        selectTab(0);
    }

    private void setTimer(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (flag){
                    try {
                        Thread.sleep(1*60*1000); //休眠
                        mHanler.sendEmptyMessage(TIMER);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    private static final int TIMER = 999;
    private static boolean flag = true;

    private Handler mHanler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case TIMER:
                    break;
                default:
                    break;
            }
        }
    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在界面销毁的地方要解绑

    }

    private void initDatas() {
        mFragments = new ArrayList<>();
        //将四个Fragment加入集合中
        mFragments.add(new MainFragment());
        mFragments.add(new LSFragment());
        mFragments.add(new LSFragment());
//        mFragments.add(new MainFragment());

        mImgWeixin.setImageResource(R.drawable.tab_home_press);

        mHomeTv.setTextColor(getResources().getColor(R.color.page_top));
//        mPerson_tv.setTextColor(getResources().getColor(R.color.text_secondary_color));
        mMsgtv.setTextColor(getResources().getColor(R.color.text_secondary_color));
        mProjectsTv.setTextColor(getResources().getColor(R.color.text_secondary_color));

        //初始化适配器
        mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {//从集合中获取对应位置的Fragment
                return mFragments.get(position);
            }

            @Override
            public int getCount() {//获取集合中Fragment的总数
                return mFragments.size();
            }

        };
        //不要忘记设置ViewPager的适配器
        mViewPager.setAdapter(mAdapter);
        //设置ViewPager的切换监听
        mViewPager.addOnPageChangeListener(new OnPageChangeListener() {
            @Override
            //页面滚动事件
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            //页面选中事件
            @Override
            public void onPageSelected(int position) {
                //设置position对应的集合中的Fragment
                mViewPager.setCurrentItem(position);
                resetImgs();
                selectTab(position);
            }

            @Override
            //页面滚动状态改变事件
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void initEvents() {
        //设置四个Tab的点击事件
        mTabWeixin.setOnClickListener(this);
        mTabFrd.setOnClickListener(this);
        mTabAddress.setOnClickListener(this);
//        mTabSetting.setOnClickListener(this);

    }

    //初始化控件
    private void initViews() {
        mHomeTv = (TextView) findViewById(R.id.id_tab_home_tv);
        mProjectsTv = (TextView) findViewById(R.id.id_tab_projects_tv);
        mMsgtv = (TextView) findViewById(R.id.id_tab_msg_tv);


//        rl_top= (RelativeLayout) findViewById(R.id.rl_top);
        mViewPager = (ViewPager) findViewById(R.id.id_viewpager);

        mTabWeixin = (LinearLayout) findViewById(R.id.id_tab_weixin);
        mTabFrd = (LinearLayout) findViewById(R.id.id_tab_frd);
        mTabAddress = (LinearLayout) findViewById(R.id.id_tab_address);

        mImgWeixin = (ImageButton) findViewById(R.id.id_tab_weixin_img);
        mImgFrd = (ImageButton) findViewById(R.id.id_tab_frd_img);
        mImgAddress = (ImageButton) findViewById(R.id.id_tab_address_img);


    }


    /**
     * 为了防止混淆更新消息的EventBus与其他管道重合
     */
    public static class ShowHideClearAll {
        public boolean isShow;

        public ShowHideClearAll(boolean isShow) {
            this.isShow = isShow;
        }
    }

    @Override
    public void onClick(View v) {
        //先将四个ImageButton置为灰色
        resetImgs();

        //根据点击的Tab切换不同的页面及设置对应的ImageButton为绿色
        switch (v.getId()) {
            case R.id.id_tab_weixin:
                selectTab(0);
                break;
            case R.id.id_tab_frd:
                selectTab(1);
                break;
            case R.id.id_tab_address:
                selectTab(2);
                break;
        }
    }

    private void selectTab(int i) {
        Window window = getWindow();
        //根据点击的Tab设置对应的ImageButton为绿色
        switch (i) {
            case 0:
                mImgWeixin.setImageResource(R.drawable.tab_home_press);
//                main_top_ll.setBackgroundColor(getResources().getColor(R.color.page_top));
//                mTvMainTop.setText("破晓");
//                mTvMainTop.setTextColor(getResources().getColor(R.color.white));
//                mHomeTv.setTextColor(getResources().getColor(R.color.page_top));
//                mMain_allread.setVisibility(View.GONE);
//                main_top_ll.setVisibility(View.VISIBLE);
//                rl_top.setVisibility(View.GONE);



                //取消设置透明状态栏,使 ContentView 内容不再覆盖状态栏
//                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//
//                //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
//                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
//
//                //设置状态栏字体颜色为黑色
//                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
//
//                window.setStatusBarColor(getResources().getColor(R.color.page_top));
//                //设置状态栏字体颜色为白色
//                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);



                break;
            case 1:
                mImgFrd.setImageResource(R.drawable.tab_home2_press);

//                main_top_ll.setBackgroundColor(getResources().getColor(R.color.white));
//                mTvMainTop.setText("项目");
//                mTvMainTop.setTextColor(getResources().getColor(R.color.page_top));
//                mProjectsTv.setTextColor(getResources().getColor(R.color.page_top));
//                mMain_allread.setVisibility(View.GONE);
//                main_top_ll.setVisibility(View.GONE);
//                Window window = getWindow();

                //取消设置透明状态栏,使 ContentView 内容不再覆盖状态栏
//                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//
//                //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
//                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
//                window.setStatusBarColor(getResources().getColor(R.color.white));
//                //设置状态栏字体颜色为黑色
//                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
//
//
//                //设置状态栏字体颜色为白色
//                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

//                rl_top.setVisibility(View.VISIBLE);
                break;
            case 2:

                mImgAddress.setImageResource(R.drawable.tab_home3_press);
//                main_top_ll.setBackgroundColor(getResources().getColor(R.color.white));
//                mTvMainTop.setText("消息中心");
//                mTvMainTop.setTextColor(getResources().getColor(R.color.page_top));
//                mMsgtv.setTextColor(getResources().getColor(R.color.black));
//                mMain_allread.setVisibility(((boolean) mMain_allread.getTag()) ? View.VISIBLE : View.GONE);
//                main_top_ll.setVisibility(View.VISIBLE);
//                rl_top.setVisibility(View.GONE);
//                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//
//                //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
//                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
//
//                window.setStatusBarColor(getResources().getColor(R.color.white));
//                //设置状态栏字体颜色为黑色
//                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
//
//
//                //设置状态栏字体颜色为白色
//                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
                break;
            case 3:
//                mImgSetting.setImageResource(R.drawable.tab_personal_press);
//                main_top_ll.setBackgroundColor(getResources().getColor(R.color.white));
//                mTvMainTop.setText("设置");
//                mTvMainTop.setTextColor(getResources().getColor(R.color.page_top));
//                mPerson_tv.setTextColor(getResources().getColor(R.color.page_top));
//                mMain_allread.setVisibility(View.GONE);
//                main_top_ll.setVisibility(View.GONE);
                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

                //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);

                window.setStatusBarColor(getResources().getColor(R.color.white));
                //设置状态栏字体颜色为黑色
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);


                //设置状态栏字体颜色为白色
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
//                rl_top.setVisibility(View.GONE);
                break;
        }
        //设置当前点击的Tab所对应的页面
        mViewPager.setCurrentItem(i);
    }

    //将四个ImageButton设置为灰色
    private void resetImgs() {
        mImgWeixin.setImageResource(R.drawable.tab_home);
        mImgFrd.setImageResource(R.drawable.tab_home2);
        mImgAddress.setImageResource(R.drawable.tab_home3);

        mHomeTv.setTextColor(getResources().getColor(R.color.text_secondary_color));
//        mPerson_tv.setTextColor(getResources().getColor(R.color.text_secondary_color));
        mMsgtv.setTextColor(getResources().getColor(R.color.text_secondary_color));
        mProjectsTv.setTextColor(getResources().getColor(R.color.text_secondary_color));
    }




    private void requestPermission() {
        // 版本判断。当手机系统大于 23 时，才有必要去判断权限是否获取
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            // 检查该权限是否已经获取
            int i = checkSelfPermission(mPermissions[0]);
            // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
            if (i != PackageManager.PERMISSION_GRANTED) {
                // 如果没有授予该权限，就去提示用户请求
                showDialogTipUserRequestPermission();
            }


        }
    }

    // 提示用户该请求权限的弹出框
    private void showDialogTipUserRequestPermission() {

        new AlertDialog.Builder(this)
                .setTitle("存储权限不可用")
                .setMessage("由于需要获取存储空间，为你存储个人信息；\n否则，您将无法正常使用")
                .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
                    @TargetApi(Build.VERSION_CODES.M)
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        requestPermissions(mPermissions, 321);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                }).setCancelable(false).show();
    }


    // 用户权限 申请 的回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 321) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    // 判断用户是否 点击了不再提醒。(检测该权限是否还可以申请)
                    boolean b = shouldShowRequestPermissionRationale(permissions[0]);
                    if (!b) {
                        // 用户还是想用我的 APP 的
                        // 提示用户去应用设置界面手动开启权限
                        showDialogTipUserGoToAppSettting();
                    } else
                        finish();
                } else {
                    Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    // 提示用户去应用设置界面手动开启权限

    private void showDialogTipUserGoToAppSettting() {

        mDialog = new AlertDialog.Builder(this)
                .setTitle("存储权限不可用")
                .setMessage("请在-应用设置-权限-中，允许APM使用存储权限来保存用户数据")
                .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 跳转到应用设置界面
                        goToAppSetting();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                }).setCancelable(false).show();
    }

    // 跳转到当前应用的设置界面
    private void goToAppSetting() {
        Intent intent = new Intent();

        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);

        startActivityForResult(intent, 123);
    }


//    private PublicNoticeDialog noticeDialog;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {


        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            exit();
//            return false;


        }
        return super.onKeyDown(keyCode, event);
    }


    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            switch (v.getId()) {


            }
        }
    };



}
